#include <QCoreApplication>
#include <QDir>
#include <QDirIterator>
#include <fstream>
#include <sstream>
#include <iostream>

int main(int argc, char *argv[])
{
    std::string replaceString   =   "newName";
    std::string copyDirFolder   =   "newProject";

    QCoreApplication a(argc, argv);

    QDir baseDir(".");

    QDir dir("./ProjetTest/");
     if (!dir.exists()){
         std::cout<<"Directory doesn't exist"<<std::endl;
     }

     dir.mkdir(QString(copyDirFolder.c_str()));


     dir.setFilter(QDir::Files | QDir::Hidden | QDir::NoSymLinks |QDir::Dirs);
     dir.setSorting(QDir::Size | QDir::Reversed);


    int i=0;

    QDirIterator iterator(dir.absolutePath(), QDirIterator::Subdirectories);
    while (iterator.hasNext()) {
        iterator.next();
        if(i==0){
            iterator.next();
            i++;
          }else if(iterator.fileName() !="." && iterator.fileName() != ".."){
            if(iterator.fileInfo().isDir()){
                std::string relativPath =dir.relativeFilePath(iterator.fileInfo().dir().absolutePath()).toStdString();
                std::string endpath="./"+copyDirFolder+"/"+relativPath+"/"+iterator.fileName().toStdString();
                if(relativPath==""){
                    endpath="./"+copyDirFolder+"/"+iterator.fileName().toStdString();
                }
                baseDir.mkpath(endpath.c_str());
            }else if(iterator.fileInfo().isFile()){

                std::string relativPath =dir.relativeFilePath(iterator.fileInfo().absolutePath()).toStdString();
                std::string endpath="./"+copyDirFolder+"/"+relativPath+"/"+iterator.fileName().toStdString();
                if(relativPath==""){
                    endpath="./"+copyDirFolder+"/"+iterator.fileName().toStdString();
                }

                QFile file(iterator.filePath());
                file.copy(endpath.c_str());


                std::ifstream myfile(endpath,std::ifstream::out | std::ifstream::in |std::ifstream::beg);

                std::stringstream buffer;
                buffer<< myfile.rdbuf();
                std::string mstring = buffer.str();

                std::string libanmestring ="%LIBNAME%";
                std::string newString = "Coucou";

                int posString =mstring.find("%LIBNAME%");

                while(  posString >=0 ){
                    mstring.replace(posString,libanmestring.size()+2,newString);
                    posString =mstring.find("%LIBNAME%");
                }



                printf( " endpath %s \n", endpath.c_str());
                printf( " file %s \n", mstring.c_str());
                myfile.close();
                std::ofstream fileopening(endpath, std::ofstream::out| std::ofstream::trunc);
                fileopening<<mstring;
                fileopening.close();

            }

          }

       }

    return a.exec();
}
